import { ref, watchEffect } from 'vue';

type Theme = 'light' | 'dark' | 'OS';

const LOCK_KEY = '__theme__';

const theme = ref<Theme>(localStorage.getItem(LOCK_KEY) as Theme || 'light');
console.log(theme.value)

const prefers = matchMedia('(prefers-color-scheme: dark)');
//console.log(prefers.matches)

const followOS = () => {
    setTheme(prefers.matches? 'dark' : 'light')
}

watchEffect(() => {
    console.log('watchEffect')
    localStorage.setItem(LOCK_KEY, theme.value);
    if(theme.value === 'OS') {
        // 根据系统的设置选择亮色或暗色
        setTheme(prefers.matches? 'dark' : 'light');
        prefers.addEventListener('change', followOS);
    } else {
        setTheme(theme.value);
        prefers.removeEventListener('change', followOS)
    }
   
})

// 修改自定义属性
function setTheme(them: Theme) {
    document.documentElement.dataset.theme =  them;
}

export default function useTheme() {
    return {
        theme
    };
}